package whitelistinterceptor

import (
	"context"
	"encoding/json"
	"github.com/go-playground/validator"
	"strconv"
	"time"
	"vpn-management-server/logger"
	"vpn-management-server/network"
	"vpn-management-server/security/code"
	"vpn-management-server/src/model/adminlogmodel"
	"vpn-management-server/src/model/adminmodel"
	Whitelistmodel "vpn-management-server/src/model/whitelistmodel"
	"vpn-management-server/src/service/adminlogservice"
	"vpn-management-server/src/service/adminservice"
)

func WhiteListValidator(ctx context.Context, request *network.NetRequest, response *network.NetResponse) bool {
	//TODO 解析json到whitelist结构体
	var whitelist Whitelistmodel.Whitelist
	err := json.Unmarshal(request.Parameters, &whitelist)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "UnMarshal Parameters to adminJson error,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "parse parameters fail"
		return false
	}
	// TODO 验证结构体字段
	valid := validator.New()
	err = valid.Struct(&whitelist)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "validate Parameters fail,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "validate parameters fail"
		return false
	}
	// TODO 验证权限 添加白名单归用户组管理员管理 不归其他管理员管
	if rank := adminservice.GetAdminRankService(ctx, request, response); rank == adminmodel.UserGroupAdmin {
		var phoneList Whitelistmodel.PhoneList
		for _, item := range whitelist.WhiteList {
			phoneList.PhoneList = append(phoneList.PhoneList, item.Phone)
		}
		// TODO 验证手机号是否有重复
		if err = valid.Struct(phoneList); err != nil {
			logger.Logger.Error("phone list have same phone", err)
			response.Code = code.BAD_REQUEST
			response.ErrorMsg = "phone list have same phone"
			return false
		} else {
			request.SetModel(&whitelist)
			return true
		}
	} else {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "have no authority")
		response.Code = code.UNAUTHORIZED
		response.ErrorMsg = "have no authority"
		return false
	}
}

func WhiteListIDsValidator(ctx context.Context, request *network.NetRequest, response *network.NetResponse) bool {
	// TODO json-->WhitelistIDs
	var whitelistIDs Whitelistmodel.WhitelistIDs
	err := json.Unmarshal(request.Parameters, &whitelistIDs)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "UnMarshal Parameters to adminJson error,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "parse parameters fail"
		return false
	}
	// TODO 验证结构体字段
	valid := validator.New()
	err = valid.Struct(&whitelistIDs)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "validate Parameters fail,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "validate parameters fail"
		return false
	}
	// TODO 验证权限 超级管理员和用户组管理员可以删除白名单 其他管理员不行
	if rank := adminservice.GetAdminRankService(ctx, request, response); rank == adminmodel.UserGroupAdmin || rank == adminmodel.SuperAdmin {
		request.SetModel(&whitelistIDs)
		return true
	} else {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "have no authority")
		response.Code = code.UNAUTHORIZED
		response.ErrorMsg = "have no authority"
		return false
	}
}

func PageValidator(ctx context.Context, request *network.NetRequest, response *network.NetResponse) bool {
	// TODO json-->WhiteListPage
	var page Whitelistmodel.WhiteListPage
	err := json.Unmarshal(request.Parameters, &page)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "UnMarshal Parameters to WhiteListPage error,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "parse parameters fail"
		return false
	}
	// TODO 验证结构体字段
	valid := validator.New()
	err = valid.Struct(&page)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "validate Parameters fail,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "validate parameters fail"
		return false
	}
	// TODO 验证权限 超级管理员/系统管理员/用户组管理员可以查看白名单
	if rank := adminservice.GetAdminRankService(ctx, request, response); rank == adminmodel.UserGroupAdmin || rank == adminmodel.SystemAdmin || rank == adminmodel.SuperAdmin {
		request.SetModel(&page)
		return true
	} else {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "have no authority")
		response.Code = code.UNAUTHORIZED
		response.ErrorMsg = "have no authority"
		return false
	}
}

func AddWhiteListLogToChan(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {

	adminlogservice.AddAdminLogToChan(adminlogservice.ChanAdminLogs, adminlogmodel.AdminLog{
		Name:      adminservice.GetCurrAdminService(ctx, request, response).Name,
		Source:    request.GetRemote(),
		Location:  "地址",
		Behavior:  "添加白名单",
		TimeStamp: strconv.FormatInt(time.Now().Unix(), 10),
	})
}

func DeleteWhiteListLogToChan(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	adminlogservice.AddAdminLogToChan(adminlogservice.ChanAdminLogs, adminlogmodel.AdminLog{
		Name:      adminservice.GetCurrAdminService(ctx, request, response).Name,
		Source:    request.GetRemote(),
		Location:  "地址",
		Behavior:  "删除白名单",
		TimeStamp: strconv.FormatInt(time.Now().Unix(), 10),
	})
}
